﻿using System;
using System.Globalization;

namespace Als.Common.String
{
    public static class TimeHelper
    {

        #region 格式化日期时间
        /// <summary>
        /// 格式化日期时间
        /// </summary>
        /// <param name="dateTime">日期时间</param>
        /// <param name="dateMode">显示模式</param>
        /// 0  yyyy-MM-dd
        /// 1  yyyy-MM-dd HH:mm:ss
        /// 2  yyyy年MM月dd日
        /// 3  yyyy年MM月dd日 HH:mm
        /// 4  yyyy/MM/dd
        /// 5  MM-dd
        /// 6  MM/dd
        /// 7  MM月dd日
        /// 8  yyyy-MM
        /// 9  yyyy/MM
        /// 10 yyyy年MM月
        /// <returns>0-9种模式的日期</returns>
        public static string FormatDate(this DateTime dateTime, string dateMode)
        {
            switch (dateMode)
            {
                case "0":
                    return dateTime.ToString("yyyy-MM-dd");
                case "1":
                    return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                case "2":
                    return dateTime.ToString("yyyy年MM月dd日");
                case "3":
                    return dateTime.ToString("yyyy年MM月dd日 HH:mm");
                case "4":
                    return dateTime.ToString("yyyy/MM/dd");
                case "5":
                    return dateTime.ToString("MM-dd");
                case "6":
                    return dateTime.ToString("MM/dd");
                case "7":
                    return dateTime.ToString("MM月dd日");
                case "8":
                    return dateTime.ToString("yyyy-MM");
                case "9":
                    return dateTime.ToString("yyyy/MM");
                case "10":
                    return dateTime.ToString("yyyy年MM月");
                default:
                    return dateTime.ToString(CultureInfo.InvariantCulture);
            }
        }
        #endregion

        #region 时间戳转换

        /// <summary>
        /// 时间戳转换成DateTime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static DateTime TryDateTime(this long time)
        {
            var timeStamp = new DateTime(1970, 1, 1);  //得到1970年的时间戳
            var t = (time + 8 * 60 * 60) * 10000000 + timeStamp.Ticks;
            var dt = new DateTime(t);
            return dt;
        }

        /// <summary>
        ///  DateTime转时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long TryTimestamp(this DateTime time)
        {
            var timeStamp = new DateTime(1970, 1, 1);  //得到1970年的时间戳
            var a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;  //注意这里有时区问题，用now就要减掉8个小时
            return a;
        }

        #endregion





    }
}
